package cn.edu.swu;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Enumeration;

public class LoginServlet  extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String type=request.getParameter("type");
        HttpSession session=request.getSession();
        if (StringUtils.isNotBlank(type)){
            try {
                if ("0".equals(type)){
                    //学生登录
                    Student student=DaoFactory.getInstance().getStudentDao().login(username,password);
                    if (student!=null){
                        session.setAttribute("user",student);
                        session.setAttribute("type",type);
                        response.sendRedirect("index.jsp");
                    }else {
                        request.setAttribute("error","用户名或密码错误");
                        request.getRequestDispatcher("login.jsp").forward(request,response);
                    }
                }else if ("1".equals(type)){
                    //老师
                    Teacher teacher=DaoFactory.getInstance().getTeacherDao().login(username,password);
                    if (teacher!=null){
                        session.setAttribute("user",teacher);
                        session.setAttribute("type",type);
                        response.sendRedirect("index.jsp");
                    }else {
                        request.setAttribute("error","用户名或密码错误");
                        request.getRequestDispatcher("login.jsp").forward(request,response);
                    }
                }else {
                    //管理员
                    Admin admin=DaoFactory.getInstance().getAdminDao().login(username,password);
                    if (admin!=null){
                        //跳转
                        session.setAttribute("user",admin);
                        session.setAttribute("type",type);
                        response.sendRedirect("index.jsp");
                    }else {
                        //用户名或密码错误
                        request.setAttribute("error","用户名或密码错误");
                        request.getRequestDispatcher("login.jsp").forward(request,response);
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else {
        }
    }
}
